import pyaudio
import wave
import os
from PyCmpltrtok.common import rand_name_on_now, get_dir_name_ext, sep

# pcm_path = r'D:\_dell7590_root\sync\1_usb\main\sci\com\ai\services\xunfei\demo\iat_pcm_16k.pcm'
# pcm_path = r'D:\_const\svn\aliyun\cmpltrtok\content\java_nb_tmp\xunfei_demo\resource\iat\16k_10.pcm'
pcm_path = r'C:\_data\_const\svn\cmpltrtok\content\java_nb_tmp\xunfei_demo\resource\iat\16k_10.pcm'
# pcm_path = r'/home/yppei/PycharmProjects/PyProjTorch1101/python_ai/category/audio/xunfei/official/_save/tts_ws_python3_demo/demo_2023_01_29_11_46_58_875556.pcm'
# pcm_path = r'/home/yppei/PycharmProjects/PyProjTorch1101/python_projs/gcwt_chat_agent/_save/tts_xunfei/demo_2023_01_29_13_45_51_962604.pcm'
_, XSRC_NAME, _ = get_dir_name_ext(pcm_path)

XDIR, XNAME, XEXT = get_dir_name_ext(os.path.abspath(__file__))
SAVE_DIR = os.path.join(XDIR, '_save', XNAME)
os.makedirs(SAVE_DIR, exist_ok=True)
WAVE_OUTPUT_FILENAME = os.path.join(SAVE_DIR, f'pcm2wav_{XSRC_NAME}_' + rand_name_on_now() + ".wav")

sep(f'Open {pcm_path}')
with open(pcm_path, 'rb') as f:
    bytes = f.read()
    wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
    wf.setnchannels(1)
    wf.setsampwidth(pyaudio.get_sample_size(pyaudio.paInt16))
    wf.setframerate(16000)
    sep(f'Writing to {WAVE_OUTPUT_FILENAME}')
    wf.writeframes(bytes)
    wf.close()
    sep('Written')
sep('All over')
